using Microsoft.EntityFrameworkCore;
using net_work.Common;
using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Config;
using net_work.Data.DTO.Cam;
using net_work.Data.Entity.Cam;
using net_work.Data.Enum.Cam;
using net_work.Data.VO.Cam;
using net_work.IRepository.Cam;

namespace net_work.Repository.Cam;

public class MessageRepository(ApplicationDbContext dbContext, IUserContext userContext)
    : Repository<Message>(dbContext), IMessageRepository
{
    public async Task<long> InsertAsync(MessageAddRequest messageAddRequest)
    {
        var message = new Message
        {
            Title = messageAddRequest.Title,
            Content = messageAddRequest.Content,
            Type = messageAddRequest.Type,
            Status = MessageStatus.Unread,
            ObjType = messageAddRequest.ObjType,
            ObjId = messageAddRequest.ObjId,
            Remark = messageAddRequest.Remark
        };
        await dbContext.Messages.AddAsync(message);
        await dbContext.SaveChangesAsync();
        return message.Id;
    }

    public async Task<bool> UpdateAsync(List<long> messageIds)
    {
        var query = await dbContext.Messages.Where(m => messageIds.Contains(m.Id)).ToListAsync();
        foreach (var message in query)
        {
            message.Status = MessageStatus.Read;
        }

        return await dbContext.SaveChangesAsync() > 0;
    }

    public async Task<PagedResult<MessageResult>> GetMessagePagedAsync(PagedRequest request)
    {
        var userId = userContext.UserId;
        var curUser = await dbContext.Users.FindAsync(userId);
        if (curUser == null)
        {
            return new PagedResult<MessageResult>();
        }

        // 获取当前用户的 ObjId
        var curPsnId = curUser.PsnId;
        long? curUserObjId = null;

        if (userContext.UserRole == "STUDENT")
        {
            curUserObjId = await dbContext.Students
                .Where(s => s.PsnId == curPsnId)
                .Select(s => s.ClassId)
                .FirstOrDefaultAsync();
        }
        else
        {
            curUserObjId = await dbContext.Teachers
                .Where(t => t.PsnId == curPsnId)
                .Select(t => t.DepId)
                .FirstOrDefaultAsync();
        }

        // 构建基础查询
        var query = dbContext.Messages.AsQueryable();

        // 根据角色构建条件
        if (userContext.UserRole == "STUDENT")
        {
            query = query.Where(m =>
                m.Type == MessageType.Bulletin ||
                (m.Type == MessageType.Notice &&
                 ((m.ObjType == MessageObjType.Class &&
                   m.ObjId == curUserObjId) ||
                  (m.ObjType == MessageObjType.User &&
                   m.ObjId == userId))));
        }
        else if (userContext.UserRole == "TEACHER")
        {
            query = query.Where(m =>
                m.Type == MessageType.Bulletin ||
                (m.Type == MessageType.Notice &&
                 ((m.ObjType == MessageObjType.Dept &&
                   m.ObjId == curUserObjId) ||
                  (m.ObjType == MessageObjType.User && m.ObjId == userId))));
        }

        // 最终的查询
        var resultQuery = from message in query
            let objName =
                (message.ObjType == MessageObjType.Class)
                    ? dbContext.AdministrativeClasses.Where(c => c.Id == message.ObjId).Select(c => c.ClassName)
                        .FirstOrDefault()
                    : (message.ObjType == MessageObjType.User)
                        ? (from user in dbContext.Users
                            join people in dbContext.People on user.PsnId equals people.Id
                            where user.Id == message.ObjId
                            select people.PsnName).FirstOrDefault()
                        : (message.ObjType == MessageObjType.Dept)
                            ? dbContext.Departments.Where(d => d.Id == message.ObjId).Select(d => d.DepName)
                                .FirstOrDefault()
                            : null // 默认情况，如果没有匹配的类型
            select new MessageResult
            {
                Id = message.Id,
                Title = message.Title,
                Content = message.Content,
                Type = message.Type,
                Status = message.Status,
                ObjType = message.ObjType,
                ObjId = message.ObjId,
                Remark = message.Remark,
                CreatedBy = message.CreatedBy,
                CreatedTime = message.CreatedTime,
                UpdatedBy = message.UpdatedBy,
                UpdatedTime = message.UpdatedTime,
                DelFlag = message.DelFlag,
                ObjName = objName
            };

        // 调用通用分页方法
        return await GetPagedQueryResultAsync(resultQuery, request);
    }
}